package com.xr.redis.util;

import com.xr.redis.holder.SpringContextHolder;
import com.xr.redis.pubsub.model.Message;
import com.xr.redis.pubsub.service.IPubSubService;
import com.xr.redis.pubsub.service.listener.AbstractPubSubListener;

/**
 * @author Arnold Yand
 * @summary 发布订阅管理器
 * @time 2018/8/4 14:44
 */
public class PubSubManager {

  /**
   * 发布消息
   * @param channel
   * @param message
   * @throws Exception
   */
  public static void publish(String channel, Message message) throws Exception {
    getPubSubService().publish(channel, message);
  }

  /**
   * 订阅频道
   * @param channel
   * @param listener
   * @throws Exception
   */
  public static void subscribe(String channel, AbstractPubSubListener listener) throws Exception {
    getPubSubService().subscribe(channel, listener);
  }

  /**
   * 获发布/订阅存服务实例
   * @return
   */
  private static IPubSubService getPubSubService() {
    IPubSubService pubSubService = SpringContextHolder.getBean(IPubSubService.class);

    if(pubSubService == null){
      throw new RuntimeException("发布/订阅服务未加载");
    }

    return pubSubService;
  }

}
